<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :lg="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            :default-expanded-keys="[100]"
            node-key="id"
            @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span v-if="data.label">
                <a class="treeTitle" :title="data.label">{{
                  data.label | ellipsis
                }}</a>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :lg="19" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item prop="tipIds">
            <el-select
              v-model="queryParams.tipIds"
              placeholder="请选择用户标签"
              clearable
              style="width: 240px"
              @change="handleTipIds"
            >
              <el-option
                v-for="val in userTipOptions"
                :key="val.id"
                :label="val.name"
                :value="val.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="searchText">
            <el-input
              v-model="queryParams.searchText"
              placeholder="请输入关键词"
              clearable
              style="width: 240px"
              @change="handleKeyword"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增用户
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="success"-->
          <!--              plain-->
          <!--              icon="el-icon-edit"-->
          <!--              size="mini"-->
          <!--              :disabled="single"-->
          <!--              @click="handleUpdate"-->
          <!--              v-hasPermi="['system:user:edit']"-->
          <!--            >修改</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="danger"-->
          <!--              plain-->
          <!--              icon="el-icon-delete"-->
          <!--              size="mini"-->
          <!--              :disabled="multiple"-->
          <!--              @click="handleDelete"-->
          <!--              v-hasPermi="['system:user:remove']"-->
          <!--            >删除</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleDataImport"
              v-hasPermi="['system:user:import']"
            >导入花名册
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
              >批量导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              placement="top"
              @confirm="handleExport"
              :title="exportTitle"
              v-hasPermi="['system:user:export']"
            >
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                slot="reference"
                @click="getExportTitle"
              >导出Excel
              </el-button>
            </el-popconfirm>
          </el-col>
          <el-col :span="1.5">
            <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              placement="top"
              @confirm="handleExportRoster"
              :title="exportTitle"
              v-hasPermi="['system:user:export']"
            >
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                slot="reference"
                @click="getExportTitle"
              >导出花名册
              </el-button>
            </el-popconfirm>
          </el-col>
          <el-col :span="1.5">
            <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              placement="top"
              @confirm="handleExportWord"
              :title="exportTitle"
              v-hasPermi="['system:user:export']"
            >
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                slot="reference"
                @click="getExportTitle"
              >导出Word
              </el-button>
            </el-popconfirm>
          </el-col>
          <el-col :span="1.5">
            <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              placement="top"
              @confirm="handleExportResume"
              :title="exportTitle"
              v-hasPermi="['system:user:export']"
            >
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                slot="reference"
                @click="getExportTitle"
              >导出简历
              </el-button>
            </el-popconfirm>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            label="序号"
            align="center"
            type="index"
            v-if="columns[0].visible"
            width="50"
          />
          <el-table-column
            label="姓名"
            align="center"
            key="userName"
            prop="userName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="工号"
            align="center"
            key="jobNumber"
            prop="jobNumber"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="手机号"
            align="center"
            key="phonenumber"
            prop="phonenumber"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="所在部门"
            align="center"
            key="deptName"
            prop="deptName"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="用户标签"
            align="center"
            key="tipIds"
            prop="tipIds"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
          >
            <template v-slot="scope">
              {{ getUserTip(scope.row.tipIds) }}
            </template>
          </el-table-column>
          <el-table-column
            label="积分"
            align="center"
            key="score"
            prop="score"
            v-if="columns[7].visible"
            width="80"
          >
            <template v-slot="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="allScoreTable(scope.row.userId)"
                >{{ scope.row.score }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="荣誉值"
            align="center"
            key="honorScore"
            prop="honorScore"
            v-if="columns[8].visible"
            width="80"
          >
            <template v-slot="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="allhonorTable(scope.row.userId)"
                >{{ scope.row.honorScore }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            key="status"
            v-if="columns[9].visible"
          >
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                active-text="正常"
                inactive-text="冻结"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <!--          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ parseTime(scope.row.createTime) }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column
            label="操作"
            align="center"
            width="280"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
                >编辑
              </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  :style="{color: 'red'}"
                  v-hasPermi="['system:user:remove']"
                >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['system:user:edit']"
              >详情
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']"
                >重置密码
              </el-button>
              <!--              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">-->
              <!--                <span class="el-dropdown-link">-->
              <!--                  <i class="el-icon-d-arrow-right el-icon&#45;&#45;right"></i>更多-->
              <!--                </span>-->
              <!--                <el-dropdown-menu slot="dropdown">-->
              <!--                  <el-dropdown-item command="handleResetPwd" icon="el-icon-key"-->
              <!--                                    v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>-->
              <!--                  <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check"-->
              <!--                                    v-hasPermi="['system:user:edit']">分配角色</el-dropdown-item>-->
              <!--                </el-dropdown-menu>-->
              <!--              </el-dropdown>-->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <el-dialog
          title="积分记录"
          :visible.sync="dialogTableVisible"
          @queryTable="getExamineUserScore"
          append-to-body
        >
          <el-table :data="scoreRecord">
            <el-table-column
              align="center"
              label="时间"
              property="examineTime"
              width="250"
            />
            <el-table-column
              property="score"
              label="积分"
              width="75"
              align="center"
            />
            <el-table-column
              property="examineTypeAppend"
              label="内容"
              align="center"
            />
          </el-table>
          <pagination
            v-show="totals > 0"
            :total="totals"
            :page.sync="scoreQueryParams.pageNum"
            :limit.sync="scoreQueryParams.pageSize"
            @pagination="getExamineUserScore"
          />
        </el-dialog>
        <el-dialog
          title="荣誉值记录"
          :visible.sync="dialogTableVisible1"
          @queryTable="getExamineUserHonor"
          append-to-body
        >
          <el-table :data="honorRecord">
            <el-table-column
              align="center"
              label="时间"
              property="examineTime"
              width="250"
            />
            <el-table-column
              property="honorScore"
              label="荣誉值"
              width="75"
              align="center"
            />
            <el-table-column
              property="examineTypeAppend"
              label="内容"
              align="center"
            />
          </el-table>
          <pagination
            v-show="totalss > 0"
            :total="totalss"
            :page.sync="honorQueryParams.pageNum"
            :limit.sync="honorQueryParams.pageSize"
            @pagination="getExamineUserHonor"
          />
        </el-dialog>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="重置密码"
      :visible.sync="open"
      width="452px"
      append-to-body
      @close="dialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            placeholder="请输入新密码"
            type="password"
            show-password
            style="width: 251px"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            placeholder="请确认密码"
            type="password"
            show-password
            style="width: 251px"
          />
        </el-form-item>
        <el-form-item>
          <div style="margin-left: 50px; padding-top: 10px">
            <el-button type="primary" plain @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitPwd">确 定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      element-loading-text="数据导入中，请稍候..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="overflow-x: hidden !important"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="uploadForm.title"
      :visible.sync="uploadForm.open"
      width="400px"
      append-to-body
      @close="cancelUpLoad"
    >
      <el-upload
        ref="uploadForm"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="uploadForm.headers"
        :action="uploadForm.url + '?updateSupport=' + uploadForm.updateSupport"
        :disabled="uploadForm.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="uploadForm.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >
            下载模板
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline; margin-left: 10px;"
            @click="importExample"
          >
            Excel样例
          </el-link>

        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelUpLoad">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      v-loading="dialogLoading1"
      element-loading-text="数据导入中，请稍候..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="overflow-x: hidden !important"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="upload1.title"
      :visible.sync="upload1.open"
      width="400px"
      append-to-body
      @close="cancelUpLoad1"
    >
      <el-upload
        ref="upload1"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload1.headers"
        :action="upload1.url + '?updateSupport=' + upload1.updateSupport"
        :disabled="upload1.isUploading"
        :on-progress="handleFileUploadProgress1"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload1.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm1">确 定</el-button>
        <el-button @click="cancelUpLoad1">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="导入数据修正"
      :visible.sync="showProblemUsers"
      width="90%"
      :before-close="() => { this.showProblemUsers = false; this.problemUsers = []; }"
      destroy-on-close
      top="50px"
      style="max-height: 800px; overflow-y: auto"
      v-if="showProblemUsers"
    >
      <ProblemUsersTemplate :problem-users="problemUsers" :problem-msg="problemMsg" @close="() => { this.showProblemUsers = false }"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  changeUserStatus,
  delUser,
  listUser,
  resetUserPwd,
  updateUser,
} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listTip } from "@/api/system/tip/tipApi";
import { listExamineUser } from "@/api/examine/user/api";
import ProblemUsersTemplate from "@/views/system/user/problemUsers";

export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 10) {
        return value.slice(0, 10) + "...";
      }
      return value;
    },
  },
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect, ProblemUsersTemplate },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.form.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      checkedDeptName: null,
      checkedTag: null,
      checkedKeyword: null,
      exportTitle: null,

      dialogLoading: false,
      dialogLoading1: false,
      // 遮罩层
      loading: true,
      resetPwdLoding: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      userTipOptions: [],
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 所有部门信息
      deptAll: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      uploadForm: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importExcel",
      },
      upload1: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importRosterExcel",
      },
      totals: 0,
      totalss: 0,
      dialogTableVisible: false,
      dialogTableVisible1: false,
      scoreRecord: [],
      honorRecord: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        approveStatus: 1,
        tipIds: undefined,
        searchText: undefined,
      },
      scoreQueryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        examineType: null,
        beginTime: null,
        endTime: null,
        userId: null,
        examineStatus: 2,
        isSubmitted: 1,
        orderByColumn: "a.examine_time",
        isAsc: "desc",
      },
      honorQueryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        examineType: null,
        beginTime: null,
        endTime: null,
        userId: null,
        examineStatus: 2,
        isSubmitted: 1,
        orderByColumn: "a.examine_time",
        isAsc: "desc",
      },
      // 列信息
      columns: [
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `姓名`, visible: true },
        { key: 2, label: `工号`, visible: true },
        { key: 3, label: `身份证号`, visible: true },
        { key: 4, label: `手机号`, visible: true },
        { key: 5, label: `所在部门`, visible: true },
        { key: 6, label: `用户标签`, visible: true },
        { key: 7, label: `积分`, visible: true },
        { key: 8, label: `荣誉值`, visible: true },
        { key: 9, label: `状态`, visible: true },
      ],
      // 表单校验
      rules: {
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
      },
      problemUsers: [],
      problemMsg: '',
      showProblemUsers: false,
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getSysUserTip();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    getExamineUserScore() {
      listExamineUser(this.scoreQueryParams).then((response) => {
        this.dialogTableVisible = true;
        this.scoreRecord = response.rows;
        this.totals = response.total;
        this.loading = false;
      });
    },
    getExamineUserHonor() {
      listExamineUser(this.honorQueryParams).then((response) => {
        this.dialogTableVisible1 = true;
        this.honorRecord = response.rows;
        this.totalss = response.total;
        this.loading = false;
      });
    },
    /** 查询用户详细积分*/
    allScoreTable(userId) {
      this.scoreQueryParams.userId = userId;
      this.scoreQueryParams.pageNum = 1;
      this.getExamineUserScore();
    },
    /**
     * 查询用户荣誉值
     * @param userId
     */
    allhonorTable(userId) {
      this.honorQueryParams.userId = userId;
      this.honorQueryParams.pageNum = 1;
      this.getExamineUserHonor();
    },
    getSysUserTip() {
      listTip().then((resp) => {
        this.userTipOptions = resp.rows;
      });
    },
    getUserTip: function (data) {
      var result = "";
      if (data !== null) {
        const dataArr = data.split(",");
        dataArr.forEach((f) => {
          var obj = this.userTipOptions.find((obj) => String(obj.id) === f);
          if (obj) {
            result += obj.name + ",";
          }
        });
        if (result.charAt(result.length - 1) === ",") {
          result = result.slice(0, -1);
        }
      }
      return result;
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.checkedDeptName = data.label;
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "正常" : "冻结";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        newPassword: undefined,
        confirmPassword: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleTipIds(val) {
      const tips = this.userTipOptions.filter(item => item.id === val);
      if (tips.length > 0) {
        this.checkedTag = tips[0].name;
      } else {
        this.checkedTag = null;
      }
    },
    handleKeyword(val) {
      this.checkedKeyword = val;
      console.log(this.checkedKeyword);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    // handleCommand(command, row) {
    //   switch (command) {
    //     case "handleResetPwd":
    //       this.handleResetPwd(row);
    //       break;
    //     case "handleAuthRole":
    //       this.handleAuthRole(row);
    //       break;
    //     default:
    //       break;
    //   }
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ name: "UserAdd", params: { id: 0 } });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({ name: "UserAdd", params: { id: row.userId } });
    },
    handleView(row) {
      this.$router.push({ name: "UserView", params: { id: row.userId } });
    },
    /** 重置密码按钮操作 */
    // handleResetPwd(row) {
    //   this.$prompt('请输入"' + row.userName + '"的新密码', "重置密码", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     closeOnClickModal: false,
    //     inputPattern: /^.{5,20}$/,
    //     inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
    //   }).then(({ value }) => {
    //       resetUserPwd(row.userId, value).then(response => {
    //         this.$modal.msgSuccess("修改成功，新密码是：" + value);
    //       });
    //     }).catch(() => {});
    // },
    handleResetPwd(row) {
      this.form.id = row.userId;
      this.open = true;
    },
    submitPwd() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.resetPwdLoding = true;
          resetUserPwd({
            userId: this.form.id,
            password: this.form.confirmPassword,
          })
            .then(() => {
              this.dialogClose();
              this.$modal.msgSuccess("密码修改成功");
            })
            .finally(() => {
              this.resetPwdLoding = false;
            });
        }
      });
    },
    dialogClose() {
      this.open = false;
      this.reset();
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      const userName = row.userName;
      this.$modal
        .confirm('是否确认删除用户"' + userName + '"？')
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    getExportTitle() {
      this.queryParams.pageNum = 1;
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.exportTitle = "确定导出";
          if (this.checkedDeptName) {
            this.exportTitle += "" + this.checkedDeptName + "下";
          } else {
            this.exportTitle += this.$store.state.user.deptName;
          }
          if (this.checkedTag) {
            this.exportTitle += this.checkedTag;
          }
          if (this.checkedKeyword) {
            this.exportTitle += "关键字为：‘" + this.checkedKeyword + "’";
          }
          this.exportTitle += "的" + this.total + "条用户数据吗？";
        }
      );
    },
    handleExport() {
      this.download(
        "system/user/exportExcel",
        {
          ...this.queryParams,
        },
        `用户数据excel导出.zip`
      );
    },
    /** 导出按钮操作 */
    handleExportWord() {
      this.download(
        "system/user/exportWord",
        {
          ...this.queryParams,
        },
        `用户数据word导出.zip`
      );
    },
    /** 导出按钮操作 */
    handleExportResume() {
      this.download(
        "system/user/exportResume",
        {
          ...this.queryParams,
        },
        `用户数据简历导出.zip`
      );
    },
    handleExportRoster() {
      this.download(
        "system/user/exportRoster",
        {
          ...this.queryParams,
        },
        `花名册导出.xls`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.uploadForm.title = "用户导入";
      this.uploadForm.open = true;
    },
    handleDataImport() {
      this.upload1.title = "花名册导入";
      this.upload1.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("system/user/importTemplateDownload", {}, `用户信息导入模板.xls`);
    },
    importExample() {
      this.download("system/user/importExampleDownload", {}, `用户信息导入样例.xls`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploadForm.isUploading = true;
      this.dialogLoading = true;
    },
    handleFileUploadProgress1(event, file, fileList) {
      this.upload1.isUploading = true;
      this.dialogLoading1 = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadForm.open = false;
      this.uploadForm.isUploading = false;
      this.dialogLoading = false;
      if (this.$refs.uploadForm) {
        this.$refs.uploadForm.clearFiles();
      }

      this.upload1.open = false;
      this.upload1.isUploading = false;
      this.dialogLoading1 = false;
      if (this.$refs.upload1){
        this.$refs.upload1.clearFiles();
      }

      if (response.code == 200) {
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
          "",
          { dangerouslyUseHTMLString: true }
        );
      } else {
        this.$set(this, 'problemUsers', response.data);
        this.problemMsg = response.msg;
        this.$confirm(`<div style="max-height: 400px; overflow-y: auto">${response.msg}</div>`, '导入结果', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '修正数据',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'myConfirm',
        }).then(() => {
          this.showProblemUsers = true;
        }).catch(() => {
          this.showProblemUsers = false;
        });
      }
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.uploadForm.submit();
    },
    cancelUpLoad() {
      this.$refs.uploadForm.clearFiles();
      this.uploadForm.open = false;
    },
    submitFileForm1() {
      this.$refs.upload1.submit();
    },
    cancelUpLoad1() {
      this.$refs.upload1.clearFiles();
      this.upload1.open = false;
    },
  },
};
</script>
<style lang="scss" scoped>

::v-deep .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}

/*打开时文字位置设置*/
::v-deep .el-switch__label--right {
  z-index: 1;
  right: 20px;
  margin-top: 7px;
  margin-left: 10px;
}

/*关闭时文字位置设置*/
::v-deep .el-switch__label--left {
  z-index: 1;
  left: 20px;
  margin-top: 8px;
  margin-right: 3px;
}

/*显示文字*/
::v-deep .el-switch__label.is-active {
  display: flex;
  flex-flow: row nowrap;
}

::v-deep .el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 60px !important;
}
</style>
